import os

import cv2
import numpy as np
import pyautogui
import time
import pyperclip
import pytesseract
from PIL import Image
from openai import OpenAI
import tkinter as tk

# DeepSeek API 相关信息
DEEPSEEK_API_KEY = ""  # 替换为实际的 API Key
DEEPSEEK_API_BASE_URL = "https://api.deepseek.com"

# 初始化 OpenAI 客户端
client = OpenAI(api_key=DEEPSEEK_API_KEY, base_url=DEEPSEEK_API_BASE_URL)

# 设置 Tesseract 路径
# 设置 TESSDATA_PREFIX 环境变量
os.environ['TESSDATA_PREFIX'] = r'E:\LenovoSoftstore\tessract'
pytesseract.pytesseract.tesseract_cmd = r'E:\LenovoSoftstore\tessract\tesseract.exe'

# 设置 @ 关键词
AT_KEYWORDS = ['11','1','111']

def get_ai_reply(user_input):
    try:
        response = client.chat.completions.create(
            model="deepseek-chat",
            messages=[
                {"role": "system", "content": "You are a helpful assistant"},
                {"role": "user", "content": user_input}
            ],
            stream=False
        )
        return response.choices[0].message.content
    except Exception as e:
        return f"调用 API 出错: {str(e)}"

# 用于记录选择区域的起始和结束坐标
start_x = None
start_y = None
end_x = None
end_y = None

def on_mouse_down(event):
    global start_x, start_y
    start_x = event.x_root
    start_y = event.y_root

def on_mouse_drag(event):
    global end_x, end_y
    end_x = event.x_root
    end_y = event.y_root

def on_mouse_up(event):
    global start_x, start_y, end_x, end_y
    if start_x is not None and end_x is not None:
        x = min(start_x, end_x)
        y = min(start_y, end_y)
        width = abs(end_x - start_x)
        height = abs(end_y - start_y)
        root.destroy()  # 关闭选择界面
        monitor_messages(x, y, width, height)

def select_region():
    global root
    root = tk.Tk()
    root.attributes('-fullscreen', True)
    root.attributes('-alpha', 0.2)  # 设置窗口透明度
    root.bind("<ButtonPress-1>", on_mouse_down)
    root.bind("<B1-Motion>", on_mouse_drag)
    root.bind("<ButtonRelease-1>", on_mouse_up)
    root.mainloop()

def preprocess_image(image):
    # 转换为灰度图像
    gray = cv2.cvtColor(np.array(image), cv2.COLOR_BGR2GRAY)
    # 高斯模糊降噪
    blurred = cv2.GaussianBlur(gray, (5, 5), 0)
    # 二值化处理
    _, thresh = cv2.threshold(blurred, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
    # 形态学开运算去除噪声
    kernel = np.ones((3, 3), np.uint8)
    opening = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel)
    # 图像锐化
    sharpen_kernel = np.array([[-1, -1, -1], [-1, 9, -1], [-1, -1, -1]])
    sharpened = cv2.filter2D(opening, -1, sharpen_kernel)
    return Image.fromarray(sharpened)

def monitor_messages(x, y, width, height):
    last_message = ""
    while True:
        try:
            # 截取用户选择的屏幕区域
            screenshot = pyautogui.screenshot(region=(x, y, width, height))
            print("截图成功")
            # 图像预处理
            preprocessed_screenshot = preprocess_image(screenshot)
            # 使用 OCR 识别截图中的文字，添加配置参数
            custom_config = r'--psm 6 --oem 3 -l chi_sim+eng --user-whitelist=ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.,?!@: '
            current_text = pytesseract.image_to_string(preprocessed_screenshot, config=custom_config)
            print("识别成功")
            # 全部识别，直接使用整个识别文本作为当前消息
            current_message = current_text.strip().replace('\n', ' ').replace('\r', ' ')
            if not current_message:
                continue

            print(current_message)

            # 分割消息为多行，逐行检查关键词
            for line in current_message.split(' '):
                if any(keyword in line for keyword in AT_KEYWORDS):
                    # 获取 AI 回复
                    for keyword in AT_KEYWORDS:
                        line = line.replace(keyword, '')
                    line = line.strip()
                    if line:
                        reply = get_ai_reply(line + "请用中文回复")
                        print(f"收到 消息: {line}\n回复: {reply}")

                        # 模拟点击输入框，这里假设鼠标当前位置为输入框位置
                        input_x, input_y = pyautogui.position()
                        pyautogui.click(input_x, input_y)
                        time.sleep(0.5)

                        message = "天狼AI: " + reply
                        pyperclip.copy(message)
                        pyautogui.hotkey('ctrl', 'v')
                        pyautogui.press('enter')

            last_message = current_message
        except pytesseract.TesseractError as te:
            print(f"OCR 识别出错: {te}")
        except Exception as e:
            print(f"发生其他错误: {e}")
        time.sleep(1)  # 每隔 1 秒检查一次新消息

if __name__ == "__main__":
    select_region()